import Vue from 'vue'
import Vuex from 'vuex'
import fetch from '../common/httpRequest'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		//是否登录 项目中改为真实登录信息判断，如token
		isLogin: uni.getStorageSync("token") ? true : false,
		//用户名称
		name: uni.getStorageSync("name") || "",
		//用户头像
		avatar: uni.getStorageSync("avatar") || "/static/mine_def_touxiang_3x.png",
		//性别
		gender: uni.getStorageSync("gender") || '1',
		shopId: uni.getStorageSync("shopId") || '',
		shopName: uni.getStorageSync("shopName") || '',
		shopEndDate: uni.getStorageSync("shopEndDate") || '',
		//登录后跳转的页面路径 + 页面参数
		returnUrl: "",
		//app版本
		version: "1.0.0",
		//当前是否有网络连接
		networkConnected: true,
		isOnline: false,
		//历史记录
		searchHistory: []
	},
	mutations: {
		login(state, payload) {
			if (payload) {
				state.name = payload.name
				state.avatar = payload.avatar
				state.gender = payload.gender
			}
			state.isLogin = true
		},
		logout(state) {
			state.isLogin = false
			state.name = ""
			state.avatar = "/static/mine_def_touxiang_3x.png"
			state.gender = ""
			state.returnUrl = ""
		},
		setReturnUrl(state, returnUrl) {
			state.returnUrl = returnUrl
		},
		networkChange(state, payload) {
			state.networkConnected = payload.isConnected
		},
		setOnline(state, payload) {
			state.isOnline = state.isOnline
		},
		setSearchHistory(state, search) {
			let searchKey = search.key
			
			let searchHistory = state.searchHistory
			searchHistory = searchHistory.filter(function(obj) {
				return obj != searchKey;
			})
			if (searchHistory.length >= 10) {
				searchHistory.shift()
			}
			searchHistory.push(searchKey)
			state.searchHistory = searchHistory
		},
		clearSearchHistory(state) {
			state.searchHistory = []
		}
	},
	actions: {
		getOnlineStatus: async function({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				// #ifndef MP-WEIXIN
				resolve(true)
				// #endif
				// #ifdef MP-WEIXIN
				if (state.isOnline) {
					resolve(state.isOnline)
				} else {
					fetch.request("/Home/GetStatus", "GET", {}, false, true, true).then((res) => {
						if (res.code == 100 && res.data == 1) {
							commit('setOnline', {
								isOnline: true
							})
							resolve(true)
						} else {
							commit('setOnline', {
								isOnline: false
							})
							resolve(false)
						}
					}).catch((res) => {
						reject(false)
					})
				}
				// #endif
			})
		}
	}
})

export default store
